﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;

namespace HomeFramework.Services
{
    internal class HomeFrameworkMessageInspector : IDispatchMessageInspector
    {
        private HomeFrameworkMessageInspector () { }
        internal readonly static HomeFrameworkMessageInspector Instance = new HomeFrameworkMessageInspector();

        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            if (!request.IsEmpty)
            {
                var path = request.Headers.GetValue("path");
                var scheme = request.Headers.GetValue("scheme");
                var binding = request.Headers.GetValue("binding");
                var name = request.Headers.GetValue("name");
                var version = request.Headers.GetValue("version");

                if (string.IsNullOrEmpty(name) | string.IsNullOrEmpty(path) | string.IsNullOrEmpty(scheme) | string.IsNullOrEmpty(binding))
                    throw new ArgumentException("Headers missing!");

                request = HomeFrameworkEngine.MessageGenerator.ProcessRequest(name, version, request, binding);
                return binding;
            }
        else
            return null;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (correlationState != null && correlationState is string)
                reply = HomeFrameworkEngine.MessageGenerator.ProcessResponse(reply, correlationState.ToString());
        }

        private Dictionary<string, string> Query(string arg)
        {
            var risp = new Dictionary<string, string>();
            foreach (var s in arg.TrimStart('?').Split('&'))
            {
                var split = s.Split('=');
                if (split.Length == 2)
                    risp.Add(s.Split('=')[0].ToLower(), s.Split('=')[1]);
            }
            return risp;
        }

    }

    internal static class HeaderExtensions
    {
        public static string GetValue(this MessageHeaders headers, string key)
        {
            var i = headers.FindHeader(key, HomeFrameworkRouterMessageInspector.HEADER_NAMESPACE);
            if (i >= 0)
                return headers.GetHeader<string>(i);
            else
                return string.Empty;
        }
    }
}